package com.xunshi.hikangvision.sevice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint(value = "/ws/{name}") // API
@Component
public class TestWebSocket {

    /***
     * 存储连接
     */
    private static ConcurrentHashMap<String, TestWebSocket> map = new ConcurrentHashMap<>();
    private Session session;
    private String name;

    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name) throws Exception{
        map.put(name, this);
        System.out.println("连接建立");
        this.session =session;
        this.name=name;
        System.out.println(session.getId());
        // 群发消息
        Set<Map.Entry<String, TestWebSocket>> entries = map.entrySet();
        for (Map.Entry<String, TestWebSocket> entry : entries) {
            sendMessage(String.valueOf(map.size()), entry.getValue().session);
        }

        sendMessage(null, session);

    }

    @OnClose
    public void onClose(Session session){
        if (map.containsKey(name)) {
            map.remove(name);
        }
        System.out.println(session);

        // 群发消息
        Set<Map.Entry<String, TestWebSocket>> entries = map.entrySet();
        for (Map.Entry<String, TestWebSocket> entry : entries) {
            sendMessage(String.valueOf(map.size()), entry.getValue().session);
        }
        System.out.println("连接关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);

    }

    @OnError
    public void onError(final Session session, final Throwable error) {
        System.out.println(String.format("socket[%s]发生错误,查找并执行退出预览&登录,错误消息是:"+error.getMessage(),session.getId()));
    }

    private void sendMessage(String message, Session toSession){
        try {
            int i = 0;
            while (i < 10) {
                log.info("服务端给客户端[{}]发送消息{}", toSession.getId(), i++);
                toSession.getBasicRemote().sendText(String.valueOf(i++));
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给客户端失败：{}", e);
        }
    }
}
